let lianJieZhuangTai = false
let XinTiaoJianCe = false

function connect() {
	return new Promise((resolve, reject) => {
		uni.connectSocket({
			url: 'ws://127.0.0.1:3000'
		});
		
		// 链接成功后调用的钩子
		uni.onSocketOpen(function(res) {
			console.log("链接成功！！")
			socketOpen = true
			xinTiao = true
			let xinTiaoInv = setInterval(() => {
				if (xinTiao) {
					xinTiao = false
					sendSocketMessage(JSON.stringify({
						type: 'ping'
					}))
				} else {
					// 链接状态 改成失败
					socketOpen = false
					// 把心跳关掉
					clearInterval(xinTiaoInv)
					xinTiaoInv = null
					repeatConnect()
				}
		
			}, 5000)
			resolve()
		});
		
		// 服务端给我们发送的内容调用的方法
		uni.onSocketMessage(function(res) {
			console.log('收到服务器内容：' + res.data);
			let data = JSON.parse(res.data)
			if (data.type === "pong") {
				xinTiao = true
			}
		});
		
		// 链接失败 调用的方法
		uni.onSocketError(function(res) {
			resolve("失败")
		});
		
	})
}

async function repeatConnect() {
	await connect()
	while(!socketOpen){
		console.log("链接成功了！123456",socketOpen,'链接状态')
		await wait(10)
		await connect()
	}

}

function wait(n){
	return new Promise((res,rej)=>{
		setTimeout(()=>{
			res()
		},n*1000)
	})
}
// 我们向服务端推送消息的方法
function sendSocketMessage(msg) {
	if (socketOpen) {
		uni.sendSocketMessage({
			data: msg
		});
	} else {
		socketMsgQueue.push(msg);
	}
}
export {
	connect
}